﻿Public Class frmEmail

    Public Property email As Email
    ' flag indicating if this is a new
    Private isAdding As Boolean

    Private Sub frmEmail_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown

        If IsNothing(email) Then
            setupFormForAdd()
        Else
            setupFormForEdit()
        End If

    End Sub

    Private Sub lnkSaveAndClose_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkSaveAndClose.LinkClicked

        If Not areInputsValid() Then
            Return
        End If

        bindFormToEmail()

        If isAdding Then
            frmEditContact.contact.emailList.Add(email)
        End If

        frmEditContact.refreshEmailAddresses()
        clearAndCloseForm()

    End Sub

    Private Sub lnkCancel_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkCancel.LinkClicked
        clearAndCloseForm()
    End Sub

    Private Sub lnkSaveAndAddAnother_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkSaveAndAddAnother.LinkClicked

        If Not areInputsValid() Then
            Return
        End If

        bindFormToEmail()

        If isAdding Then
            frmEditContact.contact.emailList.Add(email)
        End If
        setupFormForAdd()

    End Sub

    Private Sub clearAndCloseForm()
        Me.email = Nothing
        errProvider.Clear()
        Me.Hide()
    End Sub

    Private Sub setupFormForAdd()
        ' Set mode to "add" just in case it was previously "edit"
        isAdding = True
        Me.email = New Email()
        bindEmailToForm()

    End Sub

    Private Sub setupFormForEdit()

        isAdding = False
        bindEmailToForm()

    End Sub

    Private Function areInputsValid() As Boolean

        Dim isValid As Boolean = True
        errProvider.Clear()
        If (String.IsNullOrWhiteSpace(txtAddress.Text)) Then
            errProvider.SetError(txtAddress, "Address is required.")
            isValid = False
        End If

        If (String.IsNullOrWhiteSpace(txtDisplayName.Text)) Then
            errProvider.SetError(txtDisplayName, "Display Name is required.")
            isValid = False
        End If

        Return isValid
        
    End Function

    Private Sub bindEmailToForm()
        txtAddress.Text = email.address
        txtDisplayName.Text = email.displayName
    End Sub

    Private Sub bindFormToEmail()
        email.address = txtAddress.Text
        email.displayName = txtDisplayName.Text
    End Sub

End Class